package com.moleq.dialog;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import jp.co.casio.caios.framework.device.DeviceCommon;
import jp.co.casio.caios.framework.device.Drawer;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.moleq.adapter.SelectionAdapter;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.base.OnResultListener;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.mgpos.activities.R;
import com.moleq.network.CommunicationCallback;
import com.moleq.network.ConnectHandler;

public class IpaddresssSelectionDialog extends MoleQBaseDialog {

	private static final int END_SCAN_NETWORK = 0;
	private static final int START_SCAN_NETWORK = 1;
	protected static final int REFRESH_ONLINE_IP_LIST = 3;
	private OnResultListener mOnResultListener;
	private Button mButtonBack, mButtonOk, btn_report;
	private Context mContext;
	private ListView lv_station;
	private TextView tv_title;
	private SelectionAdapter mTextAndCheckboxListAdapter;

	private String mloaclIpAddress = "";
	private List<String> addressList = new ArrayList<String>();
	private ConnectHandler mNetworkMonitor = null;
	private CommunicationCallback mCmmCallback = new CommunicationCallback() {

		@Override
		public void onError(String errMsg) {
			// TODO Auto-generated method stub
			Log.e("networksetting", " error message -> " + errMsg);
			// handler.sendMessage(handler.obtainMessage(0, ""));
		}

		@Override
		public void onConnected(String ip) {

			Log.i("networksetting", ip + " is connected...");
			addOnlineIpAddress(ip);

		}

		@Override
		public void onCheckNetworkStart() {
			// mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(1,
			// ""));
		}

		@Override
		public void onCheckNetworkComplete() {
			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(REFRESH_ONLINE_IP_LIST, ""));

		}

		@Override
		public void onDisconnected(String ip) {
			Log.i("networksetting", ip + " is disconnected...");

		}
	};

	private void addOnlineIpAddress(String ip) {
		if (addressList != null && addressList.size() > 0) {
			for (int i = 0; i < addressList.size(); i++) {
				addressList.add(ip);
			}
		}
	}

	private void resetOnlineIpAddress() {
		if (addressList != null && addressList.size() > 0) {
			addressList.clear();
		}

	}

	// private void resetIpAddres(){
	// if (listItem != null && listItem.size() > 0) {
	//
	// for (int i = 0; i < listItem.size(); i++) {
	// listItem.get(i).setOnline(false);
	// }
	// mTextAndCheckboxListAdapter.notifyDataSetChanged();
	// }
	// }

	private ProgressDialog mProcessingDlg;
	private Handler mNetworkhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case END_SCAN_NETWORK:
				Log.i("networksetting", " dismiss processing dialog -> ");
				if (mProcessingDlg != null || mProcessingDlg.isShowing()) {
					mProcessingDlg.dismiss();
				}
				break;
			case START_SCAN_NETWORK:
				Log.i("networksetting", " open processing dialog -> ");
				mProcessingDlg = new ProgressDialog(mContext);
				mProcessingDlg.setTitle("");
				mProcessingDlg.setMessage("Scanning terminal, Please wait..");
				mProcessingDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				mProcessingDlg.getWindow().setWindowAnimations(android.R.style.Animation);
				mProcessingDlg.show();

				break;
			case REFRESH_ONLINE_IP_LIST:
				mTextAndCheckboxListAdapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
		}
	};

	private void scanNetwork() {
		String ip = "192.168.1.%s";
		if (mNetworkMonitor != null) {

			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(START_SCAN_NETWORK, ""));

			for (int i = 2; i < 256; i++) {
				final String ipaddress = String.format(ip, i);

				new Thread(new Runnable() {
					public void run() {
						System.out.println("connect "+ ipaddress);
						mNetworkMonitor.connect(ipaddress);
					}
				}).start();
			}

			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(END_SCAN_NETWORK, ""));
		}
	}

	public String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("WifiPreference IpAddress", ex.toString());
		}
		return null;
	}

	private Button.OnClickListener mOnClickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_cancel:
				// dismiss();
				MessageBox.show(mContext, "Do you want to terminate this action?", onClickMessageListener, MessageDialog.MESSAGE_BOX_YES_NO);
				break;
			case R.id.btn_ok:
				onReturnValue(R.id.btn_ok, mTextAndCheckboxListAdapter);
				break;
			case R.id.btn_report:
				onReturnValue(R.id.btn_report, "");
				break;
			}
		}
	};

	public OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		public void onClickYes() {
			dismiss();
		}

		public void onClickOK() {
		}

		public void onClickNo() {
		}
	};

	public void onCloseWithReturn(Object obj) {
		mOnResultListener.onReturnValue(0, obj);
		dismiss();
	}

	public IpaddresssSelectionDialog(Context context, Object base) {
		super(context, base);
		mContext = context;
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set UI layout
		this.setContentView(R.layout.dialog_perview_network_rpt);
		this.setCancelable(false);

		mButtonBack = (Button) findViewById(R.id.btn_cancel);
		mButtonBack.setOnClickListener(mOnClickListener);

		mButtonOk = (Button) findViewById(R.id.btn_ok);
		mButtonOk.setOnClickListener(mOnClickListener);

		btn_report = (Button) findViewById(R.id.btn_report);
		btn_report.setOnClickListener(mOnClickListener);

		lv_station = (ListView) findViewById(R.id.lv_station);
		tv_title = (TextView) findViewById(R.id.tv_title);

	}

	public void show() {
		super.show();

		mNetworkMonitor = new ConnectHandler(6677, mCmmCallback);

		mloaclIpAddress = getLocalIpAddress();

		resetOnlineIpAddress();

		mTextAndCheckboxListAdapter = new SelectionAdapter(mContext, addressList);
		lv_station.setAdapter(mTextAndCheckboxListAdapter);
		tv_title.setText("Ready");
		
//		new Thread(new Runnable() {
//			public void run() {
				scanNetwork();
//			}
//		}).start();
		
	}

}
